/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.utils.file;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Usage: 文件、目录工具类
 *
 * @author Charkey
 * @date 2015/7/13 13:10
 */
public class SimaFileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimaFileUtils.class);

    /**
     * <p>创建多级目录</p>
     * <p>入参中的destPath包括文件名的</p>
     *
     * @param destPath 目录
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 注意是mkdirs，创建此抽象路径名指定的目录，包括创建必需但不存在的父目录
        if (!file.getParentFile().exists()) {
            boolean mkRes = file.getParentFile().mkdirs();
            if (!mkRes) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error("Make directories failed, path: {}", file.getParentFile());
                }
            }
        }
    }

    /**
     * <p>创建多级目录</p>
     * <p>入参中的destPath不包括文件名</p>
     *
     * @param destPath 目录
     */
    public static void pureMkdirs(String destPath) {
        File file = new File(destPath);
        // 注意是mkdirs，创建此抽象路径名指定的目录，包括创建必需但不存在的父目录
        if (!file.exists()) {
            boolean mkRes = file.mkdirs();
            if (!mkRes) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error("Make directories failed, path: {}", file.getPath());
                }
            }
        }
    }

    public static void writeFile(InputStream in, String targetPath) {
        if (in == null) {
            LOGGER.error("The InputStream is null");
            return;
        }
        if (StringUtils.isBlank(targetPath)) {
            LOGGER.error("The targetPath is null");
            return;
        }
        OutputStream os = null;
        try {
            File file = new File(targetPath);
            if (file.isDirectory()) {
                throw new RuntimeException("[" + targetPath + "]是一个目录，而非一个文件路径");
            }
            os = new FileOutputStream(file);
            int len;
            byte[] ch = new byte[1024];
            while ((len = in.read(ch)) != -1) {
                os.write(ch, 0, len);
            }
            LOGGER.info("File save success: {}" + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
